/**
 * 结果选择器组件
 * 支持一键选择最优结果和混合编辑模式
 */

import React, { useState, useRef, useEffect } from 'react';
import { 
  Button, 
  Space, 
  Modal, 
  message, 
  Tooltip, 
  Dropdown,
  Menu,
  Divider,
  Tag
} from 'antd';
import { 
  SelectOutlined, 
  EditOutlined, 
  MergeOutlined,
  CopyOutlined,
  DownloadOutlined,
  StarOutlined,
  StarFilled,
  DragOutlined
} from '@ant-design/icons';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import './ResultSelector.css';

interface ModelResult {
  model: string;
  content: string;
  score?: number;
}

interface ResultSelectorProps {
  results: ModelResult[];
  selectedModel?: string;
  onSelect: (model: string) => void;
  onMerge?: (content: string) => void;
  bestModel?: string;
}

interface ContentSegment {
  id: string;
  model: string;
  content: string;
  order: number;
}

const ResultSelector: React.FC<ResultSelectorProps> = ({
  results,
  selectedModel,
  onSelect,
  onMerge,
  bestModel
}) => {
  const [isEditMode, setIsEditMode] = useState(false);
  const [segments, setSegments] = useState<ContentSegment[]>([]);
  const [mergedContent, setMergedContent] = useState('');
  const [showMergeModal, setShowMergeModal] = useState(false);
  const editorRef = useRef<HTMLTextAreaElement>(null);

  // 初始化段落分割
  useEffect(() => {
    if (isEditMode && results.length > 0) {
      const allSegments: ContentSegment[] = [];
      let segmentId = 0;
      
      results.forEach(result => {
        const paragraphs = result.content.split('\n\n').filter(p => p.trim());
        paragraphs.forEach(paragraph => {
          allSegments.push({
            id: `segment-${segmentId++}`,
            model: result.model,
            content: paragraph,
            order: segmentId
          });
        });
      });
      
      setSegments(allSegments);
    }
  }, [isEditMode, results]);

  // 处理一键选择
  const handleQuickSelect = (model: string) => {
    onSelect(model);
    message.success(`已选择 ${model} 的结果`);
  };

  // 处理选择最优
  const handleSelectBest = () => {
    if (bestModel) {
      handleQuickSelect(bestModel);
    } else {
      // 如果没有指定最优模型，选择评分最高的
      const best = results.reduce((prev, current) => 
        (current.score || 0) > (prev.score || 0) ? current : prev
      );
      handleQuickSelect(best.model);
    }
  };

  // 处理拖拽结束
  const handleDragEnd = (result: any) => {
    if (!result.destination) return;

    const items = Array.from(segments);
    const [reorderedItem] = items.splice(result.source.index, 1);
    items.splice(result.destination.index, 0, reorderedItem);

    // 更新顺序
    const updatedItems = items.map((item, index) => ({
      ...item,
      order: index
    }));

    setSegments(updatedItems);
    updateMergedContent(updatedItems);
  };

  // 更新合并内容
  const updateMergedContent = (segs: ContentSegment[]) => {
    const content = segs
      .sort((a, b) => a.order - b.order)
      .map(seg => seg.content)
      .join('\n\n');
    setMergedContent(content);
  };

  // 处理段落选择切换
  const toggleSegmentSelection = (segmentId: string) => {
    setSegments(prev => {
      const updated = prev.map(seg => 
        seg.id === segmentId 
          ? { ...seg, selected: !seg.selected }
          : seg
      );
      updateMergedContent(updated.filter(s => s.selected !== false));
      return updated;
    });
  };

  // 处理合并确认
  const handleMergeConfirm = () => {
    if (onMerge) {
      onMerge(mergedContent);
      message.success('内容已合并');
      setShowMergeModal(false);
      setIsEditMode(false);
    }
  };

  // 复制内容
  const handleCopy = (content: string) => {
    navigator.clipboard.writeText(content);
    message.success('已复制到剪贴板');
  };

  // 下载内容
  const handleDownload = (model: string, content: string) => {
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${model}_result_${Date.now()}.txt`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const actionMenu = (result: ModelResult) => (
    <Menu>
      <Menu.Item 
        key="select"
        icon={<SelectOutlined />}
        onClick={() => handleQuickSelect(result.model)}
      >
        选择此结果
      </Menu.Item>
      <Menu.Item 
        key="copy"
        icon={<CopyOutlined />}
        onClick={() => handleCopy(result.content)}
      >
        复制内容
      </Menu.Item>
      <Menu.Item 
        key="download"
        icon={<DownloadOutlined />}
        onClick={() => handleDownload(result.model, result.content)}
      >
        下载内容
      </Menu.Item>
    </Menu>
  );

  return (
    <div className="result-selector">
      <div className="selector-toolbar">
        <Space>
          <Tooltip title="选择评分最高的结果">
            <Button 
              type="primary"
              icon={<StarOutlined />}
              onClick={handleSelectBest}
            >
              选择最优
            </Button>
          </Tooltip>
          
          <Tooltip title="进入混合编辑模式">
            <Button 
              icon={<MergeOutlined />}
              onClick={() => setIsEditMode(true)}
            >
              混合编辑
            </Button>
          </Tooltip>

          {results.map(result => (
            <Dropdown 
              key={result.model}
              overlay={actionMenu(result)}
              trigger={['click']}
            >
              <Button
                type={selectedModel === result.model ? 'primary' : 'default'}
                ghost={selectedModel === result.model}
              >
                {result.model}
                {bestModel === result.model && (
                  <StarFilled style={{ marginLeft: 8, color: '#faad14' }} />
                )}
              </Button>
            </Dropdown>
          ))}
        </Space>
      </div>

      {isEditMode && (
        <div className="merge-editor">
          <div className="editor-header">
            <h3>混合编辑模式</h3>
            <p>拖拽段落重新排序，点击选择要保留的内容</p>
          </div>
          
          <DragDropContext onDragEnd={handleDragEnd}>
            <Droppable droppableId="segments">
              {(provided) => (
                <div 
                  className="segments-container"
                  {...provided.droppableProps}
                  ref={provided.innerRef}
                >
                  {segments.map((segment, index) => (
                    <Draggable 
                      key={segment.id} 
                      draggableId={segment.id} 
                      index={index}
                    >
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          className={`segment-item ${snapshot.isDragging ? 'dragging' : ''} ${segment.selected === false ? 'unselected' : ''}`}
                        >
                          <div className="segment-header">
                            <div {...provided.dragHandleProps} className="drag-handle">
                              <DragOutlined />
                            </div>
                            <Tag color={getModelColor(segment.model)}>
                              {segment.model}
                            </Tag>
                            <Button
                              size="small"
                              type="text"
                              onClick={() => toggleSegmentSelection(segment.id)}
                            >
                              {segment.selected === false ? '选择' : '取消'}
                            </Button>
                          </div>
                          <div className="segment-content">
                            {segment.content}
                          </div>
                        </div>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          </DragDropContext>

          <div className="editor-actions">
            <Space>
              <Button onClick={() => setShowMergeModal(true)}>
                预览合并结果
              </Button>
              <Button type="primary" onClick={handleMergeConfirm}>
                确认合并
              </Button>
              <Button onClick={() => setIsEditMode(false)}>
                取消
              </Button>
            </Space>
          </div>
        </div>
      )}

      <Modal
        title="合并结果预览"
        visible={showMergeModal}
        onOk={handleMergeConfirm}
        onCancel={() => setShowMergeModal(false)}
        width={800}
        okText="确认使用"
      >
        <div className="merge-preview">
          <textarea
            ref={editorRef}
            className="merge-textarea"
            value={mergedContent}
            onChange={(e) => setMergedContent(e.target.value)}
            rows={15}
          />
        </div>
      </Modal>
    </div>
  );
};

// 获取模型标签颜色
const getModelColor = (model: string): string => {
  const colors: { [key: string]: string } = {
    'gpt-4': 'purple',
    'gpt-3.5-turbo': 'blue',
    'qwen-max': 'cyan',
    'ernie-bot-4': 'green',
    'glm-4': 'orange'
  };
  return colors[model] || 'default';
};

export default ResultSelector;